﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace WXDba
{
    /// <summary>  
    /// 操作类基础封装  
    /// </summary>  
    internal class BaseOperate
    {
        /// <summary>  
        /// 当前操作上下文  
        /// </summary>  
        public WXDataContext Context { get; set; }
        /// <summary>  
        /// 获取当前上下文  
        /// </summary>  
        /// <returns></returns>  
        private WXDataContext CreateContext()
        {
            string _Key = "SentenceContext";
            if (CallContext.GetData(_Key) == null)
            {
                CallContext.SetData(_Key, new WXDataContext());
            }
            return CallContext.GetData(_Key) as WXDataContext;
        }
        public BaseOperate()
        {
            this.Context = CreateContext();
        }
        /// <summary>  
        /// 模型验证  
        /// </summary>  
        public bool IsValided<T>(T model) where T : class
        {
            DbEntityValidationResult vResult = Context.Entry<T>(model).GetValidationResult();
            if (vResult == null)
                return true;
            if (vResult.IsValid)
                return true;
            StringBuilder builder = new StringBuilder();
            foreach (DbValidationError item in vResult.ValidationErrors)
            {
                builder.Append("出错字段：" + item.PropertyName);
                builder.Append("<br />");
                builder.Append("错误描述：" + item.ErrorMessage);
                builder.Append("<br />");
            }
            throw new Exception("数据模型验证失败，" + builder.ToString());
        }
        /// <summary>  
        /// 保存数据  
        /// </summary>  
        /// <returns></returns>  
        public int Save()
        {
            return Context.SaveChanges();
        }
        /// <summary>  
        /// 标间对象为修改状态，并保存  
        /// </summary>  
        public bool SetModify<T>(T model) where T : class
        {
            Context.Entry<T>(model).State = EntityState.Modified;
            return Save() > 0;
        }
        /// <summary>  
        /// 逗号分割ID处理  
        /// </summary>  
        /// <param name="list"></param>  
        /// <returns></returns>  
        public int[] GetIntArrayFromString(string list)
        {
            if (string.IsNullOrEmpty(list))
                return new int[] { };
            string[] temp = list.Split(new[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries);
            if (temp == null || temp.Length <= 0)
                return new int[] { };
            return temp.Select(q => Convert.ToInt32(q)).ToArray();
        }
        /// <summary>  
        /// 获取逗号隔开的字符串  
        /// </summary>  
        /// <param name="list"></param>  
        /// <returns></returns>  
        public string[] GetStringArray(string list)
        {
            if (string.IsNullOrEmpty(list))
                return new string[] { };
            string[] temp = list.Split(new[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries);
            return temp;
        }

        #region 异常处理  
        /// <summary>  
        /// 添加数据异常  
        /// </summary>  
        /// <param name="ex"></param>  
        /// <returns></returns>  
        public bool Error_Add(Exception ex)
        {
            DbEntityValidationException efEx = ex as DbEntityValidationException;
            if (efEx != null)
            {
                throw new Exception("添加数据失败，" + efEx.Message);
            }

            //遍历获取内部错误内容
            string Message = ex.Message;
            Exception inner = ex.InnerException;
            while (inner != null)
            {
                Message += "\n";
                Message += "内部原因：" + inner.Message;
                inner = inner.InnerException;
            }
            throw new Exception("添加数据失败，" + Message);
        }
        /// <summary>  
        /// 修改数据异常  
        /// </summary>  
        /// <returns></returns>  
        public bool Error_Modify(Exception ex)
        {
            DbEntityValidationException efEx = ex as DbEntityValidationException;
            if (efEx != null)
            {
                throw new Exception("修改数据失败，" + efEx.Message);
            }
            string Message = ex.Message;
            if (ex.InnerException != null)
            {
                Message += "\n";
                Message += ex.InnerException.Message;
            }
            throw new Exception("修改数据失败，" + Message);
        }
        /// <summary>  
        /// 删除数据异常  
        /// </summary>  
        public bool Error_Delete(Exception ex)
        {
            DbEntityValidationException efEx = ex as DbEntityValidationException;
            if (efEx != null)
            {
                throw new Exception("删除数据失败，" + efEx.Message);
            }
            string Message = ex.Message;
            if (ex.InnerException != null)
            {
                Message += "\n";
                Message += ex.InnerException.Message;
            }
            throw new Exception("删除数据失败，" + Message);
        }
        #endregion
    }
}
